<script setup lang="ts">
import { userPwdUpdateService } from "@/api/user";
import { ref, onMounted } from "vue"
import type { userPwdInter } from "@/types/user";
import { useRouter } from "vue-router";
const router = useRouter()
const userPwdData = ref<userPwdInter>({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})
// 自定义密码校验规则
const validateRepwd = (rule: any, value: any, callback: any) => {
  if (value == '') {
    callback(new Error("请再次输入密码"))
  } else if (value !== userPwdData.value.new_pwd) {
    callback(new Error("两次输入的密码不一致"))
  } else callback()
}
const rules = {
  old_pwd: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 8, max: 16, message: '长度为8~16个非空字符且至少包含一个字母和数字', trigger: 'submit' },
  ],
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, max: 16, message: '长度为8~16个非空字符且至少包含一个字母和数字', trigger: 'submit' },
  ],
  re_pwd: [
    { validator: validateRepwd, trigger: 'submit' }
  ]
}
// 获取个人信息
import { useTokenStore } from "@/stores/token";
import { useUserInfoStore } from "@/stores/userInfo";
import { ElMessage } from "element-plus";
const userTokenStore = useTokenStore()
const userInfoStore = useUserInfoStore()
// 更新密码
const updatePwd = async () => {
  try {
    let result = await userPwdUpdateService(userPwdData.value)
    ElMessage.success('修改成功')
    // 退出登录
    userTokenStore.removeToken()
    userInfoStore.removeUserInfo()
    router.push('/login')
  } catch (err) {
    console.log(err);
  }
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>更改密码</span>
      </div>
    </template>
    <el-row>
      <el-col :span="12">
        <el-form :model="userPwdData" :rules="rules" label-width="100px" size="large">
          <el-form-item label="原密码" prop="oldPwd">
            <el-input v-model="userPwdData.old_pwd" type="password"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPwd">
            <el-input v-model="userPwdData.new_pwd" type="password"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="rePwd">
            <el-input v-model="userPwdData.re_pwd" type="password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updatePwd">提交修改</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </el-card>
</template>

<style scoped></style>